package org.example.netty.handler.channel;

import io.netty.channel.ChannelHandlerContext;
import org.example.netty.handler.channel.AbstractBusinessHandler;
import org.example.netty.handler.message.BusinessMessageTypeHandler;
import org.example.netty.handler.message.MessageHandlerFactory;
import org.example.netty.handler.message.UnknownMessageTypeHandler;
import org.example.netty.mgt.ConnectionManager;
import org.example.netty.model.CustomMessage;
import org.example.netty.model.ExtendedChannelContext;
import org.example.netty.config.NettyEndpointConfig;

import java.util.concurrent.ThreadPoolExecutor;

public class ClientBusinessHandler extends AbstractBusinessHandler {
    private ThreadPoolExecutor threadPool;
    private MessageHandlerFactory messageHandlerFactory;
    public ClientBusinessHandler(ConnectionManager connectionManager, ThreadPoolExecutor threadPool, MessageHandlerFactory messageHandlerFactory) throws NettyEndpointConfig.ValueIsEmpty {
        super(connectionManager);
        if (threadPool==null){
            throw new NettyEndpointConfig.ValueIsEmpty("该线程池不能为空");
        }
        if (messageHandlerFactory==null){
            throw new NettyEndpointConfig.ValueIsEmpty("消息处理工厂不能为空");
        }
        this.messageHandlerFactory=messageHandlerFactory;
        this.threadPool=threadPool;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CustomMessage msg) throws Exception {
        //根据不同type 寻找到对于的 消息处理handler
        final BusinessMessageTypeHandler handler = messageHandlerFactory.getHandler(msg.getType())==null?
                new UnknownMessageTypeHandler():messageHandlerFactory.getHandler(msg.getType());
        ExtendedChannelContext extendedChannelContext = connectionManager.getExtendedChannelContext(ctx.channel().id());
        //找到对于的handler之后将其放到 threadPool 进行执行
        threadPool.execute(()->{
            handler.handler(msg,extendedChannelContext);
        });
    }
}
